<?php
/**
 * (logic) 抓取运营数据
 */
namespace App\Logic\Operation;

use App\Models\Basics\SysCountry;
use App\Models\Operation\Crawl\ReviewsFile;
use App\Logic\Spider\CrawlReviews as SCrawlReviews;
use App\Models\Product\ProductClassify;
use Illuminate\Support\Facades\DB;
class CrawlReviews
{
    public static $_baseUrl = [
        'US' => 'https://www.amazon.com/dp/',
        'CA' => 'https://www.amazon.ca/dp/',
//        'JP' => 'https://www.amazon.co.jp/dp/',
        'UK' => 'https://www.amazon.co.uk/dp/',
        'DE' => 'https://www.amazon.de/dp/',
        'ES' => 'https://www.amazon.es/dp/',
        'IT' => 'https://www.amazon.it/dp/',
        'FR' => 'https://www.amazon.fr/dp/',
    ];

    public static function handle($country)
    {
        $countryId = SysCountry::getIdByCountry($country);
        if(!$countryId)return false;
        if(!array_key_exists($country,self::$_baseUrl))return false;
        $date = date('Y-m-d');

        //星级&排名
        $count = ReviewsFile::isExist($date,$countryId);
        if($count > 0)return false;
        $base = self::$_baseUrl[$country];
        set_time_limit(0);
        ini_set('memory_limit','512M');
        $data = DB::table('product_amazon_sku as pas')
            ->leftjoin('product_sku as ps', 'ps.id', '=', 'pas.psku_id')
            ->where('pas.status',1)
            ->where('pas.child_asin','like','B0%')
            ->where('pas.country_id',$countryId)
            ->pluck('pas.child_asin','ps.classify_id');
        $file = ReviewsFile::getFile($date,$countryId);
        $fp = fopen($file, 'a');
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
        fputcsv($fp, ['品类ID','品类','ASIN','Star','Ratings','B_Rank','S_Rank']);
        $n = 0;
        foreach ($data as $classifyId => $_asin){
            $asin = trim(str_replace(PHP_EOL, '', $_asin));
            if(!$asin)continue;
            $i = 1;
            do{
                $re = SCrawlReviews::reviews($base,$asin);
                $flag = ($re['star'] == 503 || $re['star'] == 0) ? false : true;
                if(!$flag){
                    $i++;
                    sleep(5);
                }
            }while(!$flag && $i <= 8);
            $title = ProductClassify::getTitleById($classifyId);
            $temp = [
                $classifyId,
                $title,
                $asin,
                $re['star'],
                $re['ratings'],
                $re['b_rank'],
                $re['s_rank'],
            ];
            fputcsv($fp, $temp);
            if ($n >= 100 && $n % 100 == 0){
                sleep(15);
            }else{
                sleep(5);
            }
            $n++;
        }
        fclose($fp);
        if(is_file($file)){
            ReviewsFile::storeFile($date,$countryId);
        }
        return true;
    }
}
